package com.xxx.baseapplication.vm

import androidx.lifecycle.LiveData
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.Transformations
import androidx.lifecycle.ViewModel
import com.xxx.baseapplication.http.WanApi
import com.xxx.mylibrary.vo.ApiResponse
import com.xxx.baseapplication.vo.PageVO

open class BaseViewModel : ViewModel() {
    val refreshTrigger = MutableLiveData<Boolean>()
    val moreLoading = MutableLiveData<Boolean>()
    val hasMore = MutableLiveData<Boolean>()
    protected val page = MutableLiveData<Int>()
    val refreshing = MutableLiveData<Boolean>()
    val loading = MutableLiveData<Boolean>()
    val autoRefresh = MutableLiveData<Boolean>()//SmartRefreshLayout自动刷新标记
    protected val api = WanApi.get()


    open fun loadMore() {
        page.value = (page.value ?: 0) + 1
        moreLoading.value = true
    }

    /**
     * 处理分页数据
     */
    fun <T> mapPage(source: LiveData<ApiResponse<PageVO<T>>>): LiveData<PageVO<T>> {
        return Transformations.map(source) {
            refreshing.value = false
            moreLoading.value = false
            hasMore.value = !(it?.data?.over ?: false)
            it.data ?: PageVO(1, ArrayList(), 0, true, 1, 20, 0)
        }
    }

}